{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Pandas 重命名列 - rename() 方法详解\n\n本教程深入讲解 `rename()` 方法的各种用法和高级技巧。\n\n## 目录\n1. rename() 基础用法\n2. 使用字典重命名\n3. 使用函数重命名\n4. 重命名索引\n5. 高级技巧"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\nimport numpy as np\nimport re"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. rename() 基础用法\n\n### 方法说明\n\n`rename()` 是最灵活的重命名方式，可以选择性地重命名特定的列或行。\n\n**语法:**\n```python\ndf.rename(columns=映射, index=映射, inplace=False, errors='raise')\n```\n\n**参数:**\n- `columns`: 字典或函数，用于重命名列\n- `index`: 字典或函数，用于重命名行\n- `inplace`: 是否直接修改原 DataFrame（默认 False）\n- `errors`: 'raise' 或 'ignore'，处理不存在的标签\n\n**特点:**\n- ✅ 可以选择性重命名部分列/行\n- ✅ 支持字典和函数两种方式\n- ✅ 默认返回新 DataFrame\n- ✅ 支持链式调用\n\n**适用场景:** 只需要重命名部分列或行时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 创建示例数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    'name': ['Alice', 'Bob', 'Charlie'],\n    'age': [25, 30, 35],\n    'city': ['NYC', 'LA', 'SF']\n})\n\nprint(\"原始 DataFrame:\")\nprint(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 重命名单列\n\n只重命名 name 列为中文。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_renamed = df.rename(columns={'name': '姓名'})\nprint(\"重命名单列:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 重命名多列\n\n同时重命名多个列。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_renamed = df.rename(columns={\n    'name': '姓名',\n    'age': '年龄',\n    'city': '城市'\n})\nprint(\"重命名多列:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例4: 使用 inplace 参数\n\n⚠️ 使用 `inplace=True` 会直接修改原 DataFrame。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_copy = df.copy()\ndf_copy.rename(columns={'name': '姓名'}, inplace=True)\nprint(\"使用 inplace=True:\")\nprint(df_copy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 使用字典重命名\n\n字典映射是最常用的重命名方式。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 部分重命名\n\n只重命名部分列，其他列保持不变。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    'col1': [1, 2, 3],\n    'col2': [4, 5, 6],\n    'col3': [7, 8, 9],\n    'col4': [10, 11, 12]\n})\n\nrename_dict = {'col1': 'A', 'col3': 'C'}\ndf_renamed = df.rename(columns=rename_dict)\nprint(\"部分重命名:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 使用字典推导式生成映射\n\n批量生成重命名映射。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将所有列名改为 'column_1', 'column_2' 等\nrename_dict = {col: f'column_{i+1}' for i, col in enumerate(df.columns)}\ndf_renamed = df.rename(columns=rename_dict)\nprint(\"使用字典推导式:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 从外部配置读取映射\n\n模拟从配置文件读取的映射关系。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 模拟从配置文件读取的映射关系\ncolumn_mapping = {\n    'col1': '第一列',\n    'col2': '第二列',\n    'col3': '第三列',\n    'col4': '第四列'\n}\n\ndf_renamed = df.rename(columns=column_mapping)\nprint(\"从配置读取映射:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. 使用函数重命名\n\n函数方式可以批量应用转换规则。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 转换为小写\n\n使用内置的 `str.lower` 函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    'Name': ['Alice', 'Bob'],\n    'Age': [25, 30],\n    'City': ['NYC', 'LA']\n})\n\nprint(\"原始 DataFrame:\")\nprint(df)\n\ndf_renamed = df.rename(columns=str.lower)\nprint(\"\\n转换为小写:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 转换为大写\n\n使用 `str.upper` 函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_renamed = df.rename(columns=str.upper)\nprint(\"转换为大写:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 使用 lambda 函数添加前缀\n\n在所有列名前添加 `col_`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_renamed = df.rename(columns=lambda x: f'col_{x}')\nprint(\"添加前缀:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例4: 使用 lambda 函数添加后缀\n\n在所有列名后添加 `_data`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_renamed = df.rename(columns=lambda x: f'{x}_data')\nprint(\"添加后缀:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例5: 自定义清理函数\n\n创建函数清理列名：转小写并替换空格为下划线。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def clean_column_name(col):\n    \"\"\"清理列名：转小写并替换空格为下划线\"\"\"\n    return col.lower().replace(' ', '_')\n\ndf_messy = pd.DataFrame({\n    'User Name': ['Alice', 'Bob'],\n    'User Age': [25, 30],\n    'Home City': ['NYC', 'LA']\n})\n\ndf_clean = df_messy.rename(columns=clean_column_name)\nprint(\"使用自定义函数:\")\nprint(df_clean)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. 重命名索引\n\n`rename()` 也可以重命名行索引。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 使用字典重命名索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    '姓名': ['张三', '李四', '王五'],\n    '年龄': [25, 30, 35]\n}, index=['a', 'b', 'c'])\n\nprint(\"原始 DataFrame:\")\nprint(df)\n\ndf_renamed = df.rename(index={'a': '第一行', 'b': '第二行'})\nprint(\"\\n重命名索引:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 使用函数重命名索引\n\n将索引转换为大写。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_renamed = df.rename(index=str.upper)\nprint(\"索引转大写:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 同时重命名列和索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_renamed = df.rename(\n    columns={'姓名': 'name', '年龄': 'age'},\n    index={'a': 'row1', 'b': 'row2', 'c': 'row3'}\n)\nprint(\"同时重命名列和索引:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. 高级技巧\n\n一些实用的高级重命名技巧。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 技巧1: 链式重命名\n\n可以连续调用多个 `rename()`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    'a': [1, 2, 3],\n    'b': [4, 5, 6],\n    'c': [7, 8, 9]\n})\n\ndf_renamed = (df\n    .rename(columns={'a': 'A'})\n    .rename(columns={'b': 'B'})\n    .rename(columns={'c': 'C'})\n)\nprint(\"链式重命名:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 技巧2: 条件重命名\n\n只重命名满足特定条件的列。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    'col_1': [1, 2],\n    'col_2': [3, 4],\n    'data_1': [5, 6],\n    'data_2': [7, 8]\n})\n\n# 只重命名以 'col_' 开头的列\nrename_dict = {col: col.replace('col_', 'column_') \n               for col in df.columns if col.startswith('col_')}\ndf_renamed = df.rename(columns=rename_dict)\nprint(\"条件重命名:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 技巧3: 使用正则表达式\n\n使用正则表达式进行复杂的重命名。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    'col_1_data': [1, 2],\n    'col_2_data': [3, 4],\n    'col_3_data': [5, 6]\n})\n\ndef rename_with_regex(col):\n    # 将 'col_X_data' 改为 'column_X'\n    return re.sub(r'col_(\\d+)_data', r'column_\\1', col)\n\ndf_renamed = df.rename(columns=rename_with_regex)\nprint(\"使用正则表达式:\")\nprint(df_renamed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 技巧4: 批量添加前后缀（简化方法）\n\n使用 `add_prefix()` 和 `add_suffix()` 更简单。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    'A': [1, 2],\n    'B': [3, 4],\n    'C': [5, 6]\n})\n\n# 使用 add_prefix 和 add_suffix\ndf_prefix = df.add_prefix('col_')\nprint(\"添加前缀（更简单）:\")\nprint(df_prefix)\n\ndf_suffix = df.add_suffix('_data')\nprint(\"\\n添加后缀（更简单）:\")\nprint(df_suffix)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 技巧5: 处理重复列名\n\n为重复的列名添加序号。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame([[1, 2, 3]], columns=['A', 'B', 'A'])\nprint(\"重复列名的 DataFrame:\")\nprint(df)\nprint(f\"列名: {df.columns.tolist()}\")\n\n# 为重复列名添加序号\ncols = pd.Series(df.columns)\nfor dup in cols[cols.duplicated()].unique():\n    cols[cols[cols == dup].index.values.tolist()] = [dup + '_' + str(i) if i != 0 else dup \n                                                       for i in range(sum(cols == dup))]\ndf.columns = cols\nprint(\"\\n处理后:\")\nprint(df)\nprint(f\"列名: {df.columns.tolist()}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结\n\n### rename() 方法的优势\n\n1. **灵活性**: 支持字典、函数、lambda 表达式\n2. **选择性**: 可以只重命名部分列\n3. **安全性**: 默认返回新 DataFrame，不修改原数据\n4. **链式调用**: 支持方法链，代码更简洁\n\n### 使用建议\n\n| 场景 | 推荐方法 |\n|------|----------|\n| 重命名少数列 | `rename(columns={...})` |\n| 重命名所有列 | 直接赋值 `df.columns = [...]` |\n| 批量转换（大小写等） | `rename(columns=str.lower)` |\n| 添加前后缀 | `add_prefix()` / `add_suffix()` |\n| 复杂转换 | 自定义函数 + `rename()` |\n\n### 关键要点\n\n1. `rename()` 默认返回新 DataFrame\n2. 使用 `columns` 参数重命名列\n3. 使用 `index` 参数重命名索引\n4. 支持字典和函数两种方式\n5. 避免使用 `inplace=True`\n6. 可以使用正则表达式进行复杂重命名\n7. `add_prefix()` 和 `add_suffix()` 是添加前后缀的简便方法"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}